home *** CD-ROM | disk | FTP | other *** search
- Path: news.magi.com!news!news.magi.com
- From: nredding@magi.com (Neil Redding)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Fri, 19 Jan 1996 22:45:36 -0500
- Organization: Magi Data Consulting
- Message-ID: <nredding-1901962245370001@magi04p72.magi.com>
- References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com>
- NNTP-Posting-Host: magi04p72.magi.com
-
- In article <4dp5dk$t3r@newsbf02.news.aol.com>, babycox@aol.com (BabyCox) wrote:
-
- >>#define ISPOW2(x) (((x) & 1) ^ 1)
- >
- >That will not work, it returns the next lowest MULTIPLE of two, here's
- >what I would do:
- >
- >Boolean IsPowerOfTwo(long x)
- >{
- > for(short y = 0;y<=31;y++)
- > {
- > if (x = 1) return true;
- > x >>= 1;
- > }
- > return false;
- >}
-
- Even worse, this returns true unless x == 0.
-
- If n is a power of 2, repeatedly multiplying n by 2 will eventually give you
- 2**32 == 0 when it overflows. Also shifting left one bit ( n<<1) is the same
- as multiplying by 2.
- Thus:
-
-
- Boolean IsPowerOfTwo( unsigned long n )
- {
- short k = 31;
- if ( n == 0 )
- return false;
- while ( k-- > 0 )
- if ( (n <<= 1 ) == 0 )
- return true;
- return false;
- }
-
- --
- Neil Redding
- Ottawa, Canada
-